import React, { useEffect, useRef, useState } from "react";
import { Button, StyleSheet } from "react-native";
import Video from "react-native-video";

const Play = props => {

  let currentMusic = props.currentMusic;
  // useEffect(() => {
  //   switch (currentMusic.from) {
  //     case '163':
  //
  //   }
  // },[currentMusic])
  const onEnd = () => {
    if(props.musicList.length>0) {
      let index = props.musicList.findIndex((r) => {
        return r.id === currentMusic.id && r.name === currentMusic.name;
      });
      if(index + 1 < props.musicList.length)
        props.setCurrentMusic(props.musicList[index+1])
      else
        props.setCurrentMusic(props.musicList[0])
    }
    props.setCurrentTime(0);
    //console.log('onEnd');
  };


  const ref = useRef(null);
  function onBuffer() {
    //console.log('onBuffer');
  }
  function onError() {
    //console.log('onError');
  }
  const onProgress = data => {
    if (!props.isPressed && props.seeked) {
      // 尽量不要自己去更新DOM
      //this.refs.seekBar.setProgress(Math.round(data.currentTime));
      curr(data.currentTime)
      ////console.log("onProgress: " + data.currentTime);
    }
  };
  function curr(progress) {
    let currentTime = Math.round(props.currentTime);
    let newTime = Math.round(progress * 1000); // 单位：毫秒
    if (currentTime !== newTime) {
      // 用整数比较，减少刷新次数
      props.setCurrentTime(newTime);
      ////console.log("setCurrentTime: " + newTime);
    }
  }
  const onLoad = data => {
    props.setDuration(data.duration*1000);
    props.setPlayer(ref)
    //console.log('onLoad: ' + data.duration);
  };
  return (
    <Video
      source={{uri:currentMusic.resource}}// Can be a URL or a local file.
      ref={ref}
      style={styles.hidden}
      onError={onError}
      paused={!props.play}
      onLoad={onLoad}
      onProgress={onProgress}
      onEnd={onEnd}
      repeat={false}
      playInBackground={true}
      onSeek={()=>props.setSeeked(true)}
    />
  );


};
const styles = StyleSheet.create({
  hidden: {
    width: 0,
    height: 0,
  },
})
export default Play;
